<script setup>
import { ref } from 'vue'
import { NMenu } from 'naive-ui'
import { EXT_OPT, FindProxyForURL } from './constants'
import { initOpt } from './utils'

const options = ref(initOpt('POPUP'))
chrome.storage.sync.get(EXT_OPT, ({ opt_ext }) => {
  for (let op in opt_ext) {
    options.value.splice(options.value.length - 1, 0, opt_ext[op])
  }
})

const mode = ref('')
chrome.storage.sync.get(['mode'], (data) => {
  if (data.mode) {
    mode.value = data.mode
  }
})

const closePopup = (response) => {
  console.log("sendMessage response =", response)
  window.close()
}

const handleUpdate = (val) => {
  mode.value = val
  chrome.storage.sync.set({ mode: val })

  switch (val) {
    case 'direct':
      chrome.runtime.sendMessage({ mode: 'direct' }, closePopup)
      break
    case 'system':
      chrome.runtime.sendMessage({ mode: 'system' }, closePopup)
      break
    case 'switch':
      chrome.storage.sync.get('pacScript', (data) => {
        console.log('pacScript', data.pacScript)
        chrome.runtime.sendMessage({
          mode: 'pac_script',
          pacScript: {
            data: data.pacScript || FindProxyForURL,
            mandatory: true
          }
        }, closePopup)
      })
      break
    default:
      chrome.storage.sync.get(EXT_OPT, ({ opt_ext }) => {
        const { scheme, host, port } = opt_ext[val].value
        chrome.runtime.sendMessage({
          mode: 'fixed_servers',
          rules: {
            singleProxy: {
              scheme,
              host,
              port: parseInt(port)
            },
            bypassList: ['127.0.0.1', 'localhost', '[::1]']
          }
        }, closePopup)
      })
  }
}
</script>

<template>
  <n-menu
    :options="options"
    style="width: 150px;"
    :indent="15"
    :value="mode"
    :on-update:value="handleUpdate"
  />
  <div class="options">
    <a href="./options.html" target="_blank">选项</a>
  </div>
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
}
.n-menu {
  padding-bottom: 0;
}
.n-menu .n-menu-item {
  height: 28px;
  margin-top: 0;
}
.n-menu .n-menu-item::before {
  left: 0;
  right: 0;
}
.options {
  padding-left: 15px;
  width: 135px;
  line-height: 28px;
  border-top: 1px solid #ececec;
}
.options a {
  display: block;
  color: #515457;
  text-decoration: none;
}
.options a:hover {
  color: #36ad6a;
}
</style>
